﻿var TypesObject = function (strCompanyCode, strCulture, strVersion, strSourceFilter, Search, Sorting, Total) {
    /*
        Handles Types toggle area	
        strCompanyCode - [string] the company code in question
        strCulture - [string] the culture code of the tool
        strVersion - [string] the version of the tool
        strSourceFilter - [string] a coma separated string of the source IDs as integer of the sources that are allowed
        Search - [object] the [SearchObject] for this tool
        Sorting - the [SortingContainerObject] for this tool
        Total - the [TotalContainerObject] for this tool
    */
    this.root = $('#Types');
    this.typeFilter = ''; //a coma separated type filter
    this.sourceFilter = ''; //a coma separated source filter
    this.hasFilter = false;
    this.hasTypeFilter = false;
    this.canHaveTypes = true;
    this.toggleTypeCall = null; //the call that will be called if a type button has been toggled
    this.dataLoadedCall = null; //the call that will be called when the types data is loaded
    this.removeNewsCall = null; //the call that will be called when the news of the main tool need to be cleared
    this.errorCall = null;//the call that will be called when the types could not be loaded
    this.periodText

    var This = this
		, TypesArr = []
		, isOthersActive = false
		, strOthersGroup_Type = ''//is the others group types as a coma separated string
    ;

    /********************************************************************************
	These variables are commented out, because they need to be added using prototype.
	---------------------------------------------------------------------------------
	
	this.strOthersGroupText = 'Others';
	this.CustomNames = []; //an array holding all of the custom names as <ClientCustomTypeName> gotten from the server
	this.OthersGroup = []; //an array containing the types as <ClientTypeOthersGroupItem> that belong into others types group.
	this.CustomGroups = []; //an array that holds the custom groups defined by support and made by makeCustomGroups()
	
	this.defaultSourceTypeFilter = ''; //string a coma separated type filter
		
	********************************************************************************/

    this.defaultTypeFilter = ''; //a coma separated type filter	

    this.get = function (dateFrom, dateTo, changePeriodCall) {
        /*
            gets the Types for the the current selection
            dateFrom  - JS DateObject, the date from with the data will be read
            dateTo - JS DateObject, the date to with the data will be read
            changePeriodCall - [optional] Function, is the function that can change the period marker when given as a string to the function.		
        */
        this.hasFilter = true;
        this.hasTypeFilter = true;
        this.typeFilter = This.defaultTypeFilter;

        this.root.animate({
            height: 0
			, opacity: 0
        }, null, null, function () {
            Utility.jQueryAjaxRetryCall(Utility.baseURI + './Main/GetTypes/', {
                data: {
                    'strDateFrom': Utility.formatDate(dateFrom, 'dd/MM/yyyy', false)
					, 'strDateTo': Utility.formatDate(dateTo, 'dd/MM/yyyy', false)
					, searchPhrase: Search.searchText
					, companyCode: strCompanyCode
					, lang: strCulture
					, v: strVersion
                },
                dataType: 'json',
                success: function (data) {

                    Sorting.hide();
                    Total.hide();
                    loadTypes(data.Data, data.AllTypes);
                    if (typeof changePeriodCall == 'function') {
                        changePeriodCall(data.period);
                    }
                    if (typeof This.dataLoadedCall == 'function') {
                        This.dataLoadedCall();
                    }
                },
                error: function () {
                    if (typeof This.errorCall == 'function') {
                        This.errorCall();
                    }
                }
            });
        });
    };
    this.remove = function () {

        This.hasFilter = false;
        this.hasTypeFilter = strSourceFilter.length && This.defaultTypeFilter.length ? true : false;
        this.typeFilter = This.defaultTypeFilter;
        this.sourceFilter = strSourceFilter;
        Utility.Effects.hide(This); //removes the types toggle selection area
    }

    this.getCustomName = function (name, sourceID, typeID, useOthersGroup) {
        /*
            Returns the correct type name i.e. returns the custom type name if one has been set for the type. 
            If no custom type name has been set for the given type, then the [name] will be returned instead.
            name - [string] The original type name from the DB
            sourceID - [int] The source ID of the type
            typeID - [int] The type ID of the type
            useOthersGroup - [Optional] Boolean, if set to true, then if the type belongs to the others group, then type will be set as the the others group text
        */
        if (typeof useOthersGroup != 'boolean')
            useOthersGroup = false;

        var obj
			, ret = name
			, index = this.CustomNames.length
        ;

        while (index--) {
            obj = this.CustomNames[index];
            if (obj.sourceID = sourceID && obj.typeID == typeID) {
                ret = obj.name;
                break;
            }
        }

        if (useOthersGroup) {
            if (isFromOthersGroup(sourceID, typeID)) {
                ret = This.strOthersGroupText;
            }
        }

        return ret;
    };

    function isFromOthersGroup(sourceID, typeID) {
        /*
            Checks to see if a givven type is from the others group or not. Returns a boolean value that shows if the type belongs to the others group or not.
            sourceID - [int] The source ID of the type
            typeID - [int] The type ID of the type
        */
        var obj
			, index = This.OthersGroup.length
        ;

        index = This.OthersGroup.length;
        while (index--) {
            obj = This.OthersGroup[index];
            if (typeID == obj.typeID && sourceID == obj.sourceID) {
                return true;
            }
        }
        return false;
    }

    function loadTypes(arr, allTypesArr) {
        /*
            Loads the press release types onto the tool
            arr - an array containing the raw <TypeData> objects
        */
        if (typeof arr == 'object' && arr != null) {
            if (typeof arr.length == 'number') {
                TypesArr = arr;
            }
        }

        This.root.empty();
        This.typeFilter = This.defaultTypeFilter;
        This.sourceFilter = '';

        var i, index, item, hasOthers = false, dom, hasCustomType, j, obj;

        if (typeof This.removeNewsCall == 'function') {
            This.removeNewsCall();
        }

        for (i = 0; i < TypesArr.length; i++) {

            item = TypesArr[i];

            //Checks if the item belongs to the others group
            if (isFromOthersGroup(item.SourceID, item.TypeID)) {
                hasOthers = true;
                continue;
            }

            //Sets the custom name for the tab if exists.
            item.Name = This.getCustomName(item.Name, item.SourceID, item.TypeID);

            //Makes the Type toggle
            item.isSelected = false;
            item.dom = $('<button>').addClass('Type').text(item.Name)[0];

            item.dom.intTypeIndex = i;
            item.dom.onclick = function () {
                togleType(parseFloat(this.intTypeIndex));
            }

            This.root.append(item.dom);
        }


        for (i = 0; i < This.CustomGroups.length; i++) {

            item = This.CustomGroups[i];

            hasCustomType = false;
            index = item.Types.length;
            while (index-- && !hasCustomType) {
                obj = item.Types[index];
                for (j = 0; j < allTypesArr.length && !hasCustomType; j++) {
                    if (obj.TypeID == allTypesArr[j].TypeID && obj.SourceID == allTypesArr[j].SourceID) {
                        hasCustomType = true;
                    }
                }
            }

            if (!hasCustomType) {
                continue;
            }

            dom = $('<button>').addClass('Type').text(item.name)[0];
            dom.buttonIndex = i;
            item.isActive = false;
            dom.onclick = function () {
                var item = This.CustomGroups[parseFloat(this.buttonIndex)];
                item.isActive = !item.isActive;
                this.className = item.isActive ? 'Type TypeSelected' : 'Type';
                makeFilter();
            }
            This.root.append(dom);
        }

        isOthersActive = false;
        if (hasOthers) {
            if (This.OthersGroup.length > 0) {
                dom = $('<button>').addClass('Type').text(This.strOthersGroupText)[0];
                dom.isActive = '0';
                dom.onclick = function () {
                    this.isActive = this.isActive == '0' ? '1' : '0';
                    isOthersActive = this.isActive == '1';
                    togleOthers(this);
                }

                This.root.append(dom);
            }
        }

        Utility.Effects.show(This);
    }

    function togleOthers(dom) {
        /*
            The function that will be called when the others type is toggled
            dom - [DOM Object] The Others tab
        */
        dom.className = isOthersActive ? 'Type TypeSelected' : 'Type';

        makeFilter();
    }
    function togleType(index) {
        var obj = TypesArr[index];
        obj.isSelected = !obj.isSelected;
        obj.dom.className = obj.isSelected ? 'Type TypeSelected' : 'Type';

        makeFilter();
    }
    function makeFilter() {
        /*
            Makes a the new filter and calls the [this].toggleTypeCall when complete
        */

        var index = TypesArr.length
			, sourceArr = []
			, obj
			, j
        ;

        sourceArr = []; //strSourceFilter.length ? strSourceFilter.split(',') : [];

        This.typeFilter = This.defaultTypeFilter;
        while (index--) {
            obj = TypesArr[index];
            if (!obj.isSelected)
                continue;
            if (This.typeFilter.length)
                This.typeFilter += ',';
            This.typeFilter += obj.TypeID;

            //Checks if the source already exists in the sourceArr
            j = sourceArr.length;
            while (j--) {
                if (sourceArr[j] == obj.SourceID) {
                    break;
                }
            }
            //Adds in the missing source if needed
            if (j < 0) {
                sourceArr.push(obj.SourceID);
            }
        }

        //Adds in the custom types to the filters
        index = This.CustomGroups.length;
        while (index--) {
            obj = This.CustomGroups[index];
            if (!obj.isActive) {
                continue;
            }

            This.typeFilter += (This.typeFilter.length ? ',' : '') + obj.typeIDs;

            //Adds in the source filters
            j = obj.sourceIDs.length;
            while (j--) {
                if (sourceArr.indexOf(obj.sourceIDs[j]) == -1) {
                    sourceArr.push(obj.sourceIDs[j]);
                }
            }
        }

        if (isOthersActive) {
            This.typeFilter += (This.typeFilter.length ? ',' : '') + strOthersGroup_Type;

            //Adds in the sources from the others group
            index = This.OthersGroup.length;
            while (index--) {
                obj = This.OthersGroup[index];
                //Checks if the source already exists in the sourceArr
                j = sourceArr.length;
                while (j--) {
                    if (sourceArr[j] == obj.sourceID) {
                        break;
                    }
                }
                //Adds in the missing source if needed
                if (j < 0) {
                    sourceArr.push(obj.sourceID);
                }
            }
        }

        //Creates the SourceFilter
        This.sourceFilter = '';
        index = sourceArr.length;
        while (index--) {
            if (This.sourceFilter.length)
                This.sourceFilter += ',';
            This.sourceFilter += sourceArr[index];
        }

        if (typeof This.toggleTypeCall == 'function') {
            This.toggleTypeCall();
        }
    }

    function _init() {
        if (typeof strCompanyCode != 'string')
            strCompanyCode = '';
        if (typeof strSourceFilter != 'string')
            strSourceFilter = '';
        if (typeof This.strOthersGroupText != 'string')
            This.strOthersGroupText = 'Others';
        if (typeof This.CustomNames != 'object' || This.CustomNames == null)
            This.CustomNames = [];
        if (typeof This.OthersGroup != 'object' || This.OthersGroup == null)
            This.OthersGroup = [];


        var index = This.OthersGroup.length;
        strOthersGroup_Type = '';
        while (index--) {
            if (strOthersGroup_Type.length)
                strOthersGroup_Type += ',';
            strOthersGroup_Type += This.OthersGroup[index].typeID
        }

        if (typeof This.defaultSourceTypeFilter == 'string') {

            var arr, itemArr, item, source, type;
            arr = This.defaultSourceTypeFilter.split(',');

            index = arr.length;
            while (index--) {
                item = arr[index].split('-');
                if (item.length == 2) {
                    try {
                        source = parseFloat(item[0]);
                        type = parseFloat(item[1]);

                    } catch (e) {
                        continue;
                    }

                    if (This.defaultTypeFilter.length) {
                        This.defaultTypeFilter += ',';
                    }
                    This.defaultTypeFilter += type;

                    if (strSourceFilter.length) {
                        strSourceFilter += ',';
                    }
                    strSourceFilter += source;
                }
            }
        }

        This.sourceFilter = strSourceFilter;
        This.typeFilter = This.defaultTypeFilter;
        This.hasTypeFilter = strSourceFilter.length && This.defaultTypeFilter.length ? true : false;
        This.canHaveTypes = !This.hasTypeFilter;

        This.root.animate({
            height: 0
			, opacity: 0
        }, 0);
    }
    _init();
};